// pages/patientPages/order/sureOrder/sureOrder.js
const ajax = require("../../../../utils/ajax.js")
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    doctorInfo: {},
    orderDate: "",
    orderTimes: "",
    userInfo: {},
    remark: "",
    doctorId: "",
    cases: [],
    imgUrl: [],
    fromPath:""
  },
  deleteClick: function(e) {
    let index = e.currentTarget.dataset.index;
    let arrImg = this.data.imgUrl;
    let arrCases = this.data.cases;
    arrImg.splice(index, 1)
    arrCases.splice(index, 1)
    this.setData({
      imgUrl: arrImg,
      cases: arrCases
    })

  },
  lookImg: function(e) {
    let url = e.currentTarget.dataset.url
    let that = this
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: that.data.imgUrl // 需要预览的图片http链接列表
    })
  },
  wxLogin: function () {
    //授权openid
    wx.login({
      success: function (res) {
        if (res.code) {
          ajax.request({
            url: app.url.miniGetCode,
            data: {
              code: res.code
            }
          }).then(data => {
            if (data.code !== 200) {
              return wx.showToast({
                title: data.msg,
                icon: "none"
              })
            }
            wx.setStorageSync("openid", data.data.openid)
            that.judgePay(data.data.openid)
          })
        }
      }
    })
  },
  judgePay:function(openid){
    //微信支付
    ajax.request({
      url: app.url.appointmentAddOrder,
      data: {
        doctor_id: this.data.doctorId,
        real_name: this.data.userInfo.real_name,
        idcard: this.data.userInfo.idcard,
        sex: this.data.userInfo.sex,
        phone: this.data.userInfo.phone,
        date: this.data.orderDate,
        cases: this.data.cases,
        times: this.data.orderTimes,
        remark: this.data.remark
      }
    }).then(res => {
      if (res.code !== 200) {
        return wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 1000
        })
      }
      ajax.request({
        url: app.url.appointmentOrderPay,
        data: {
          pay_no: res.pay_no,
          openid: openid
        }
      }).then(data => {
        if (data.code !== 200) {
          return wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000
          })
        }
        wx.requestPayment({
          'timeStamp': data.data.timeStamp,
          'nonceStr': data.data.nonceStr,
          'package': data.data.package,
          'signType': data.data.signType,
          'paySign': data.data.paySign,
          'success': function (res) {
            wx.showToast({
              title: '支付成功',
              icon: "none"
            })
            wx.redirectTo({
              url: '/pages/userPages/history/history'
            })
          },
          'fail': function (res) {
            wx.showToast({
              title: '支付失败',
              icon: "none"
            })
          }
        })
      })
    })
  },
  payClick:function(){
    let openid = wx.getStorageSync("openid")
    let that = this
    if (openid) {
      that.judgePay(openid)
    } else {
      that.wxLogin()
    }
  },
  freeClick:function(){
    wx.showLoading({
      title: '',
    })
    ajax.request({
      url: app.url.appointmentAdd,
      data: {
        doctor_id: this.data.doctorId,
        real_name: this.data.userInfo.real_name,
        idcard: this.data.userInfo.idcard,
        sex: this.data.userInfo.sex,
        phone: this.data.userInfo.phone,
        date: this.data.orderDate,
        cases: this.data.cases,
        times: this.data.orderTimes,
        remark: this.data.remark
      }
    }).then(res => {
      if (res.code == 200) {
        wx.hideLoading()
        let num = 6
        let timer = setInterval(() => {
          wx.showToast({
            title: '订座成功(' + num + "s后返回)",
            icon: "none",
            duration: 1000,
            success: function () {
              if (num < 1) {
                clearInterval(timer)
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
          num -= 1;
        }, 1000)

      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 1000
        })
      }
    })
  },
  submitClick: function() {
    let that=this
    ajax.request({
      url: app.url.isCanSpecial,
      data:{
        doctor_id: this.data.doctorId,
        date: this.data.orderDate,
        times: this.data.orderTimes
      }
    }).then(res=>{
      if(res.code==300){
        return wx.showToast({
          title:re.msg,
        })
      }
      if(res.money>0){
        that.payClick()
      }else{
        that.freeClick()
      }
    })
  },
  uploadImg: function() {
    let that = this;
    //上传图片
    let imgArr = this.data.cases;
    let imgUrlArr = this.data.imgUrl;
    wx.chooseImage({
      count: 5,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {

        let token = wx.getStorageSync("token")
        wx.showLoading({
          title: '拼命上传中..',
          icon: "none"
        })
        let pathArr = res.tempFilePaths
        for (var i = 0; i < pathArr.length; i++) {
          wx.uploadFile({
            url: app.url.upload, //仅为示例，非真实的接口地址
            filePath: res.tempFilePaths[i],
            name: 'file',
            formData: {
              token: token
            },
            success: function(img) {
              let data = JSON.parse(img.data)
              if (data.code !== 200) {
                return wx.showToast({
                  title: data.msg,
                  icon: "none"
                })
              }
              imgArr.push(JSON.parse(img.data).data.path)
              imgUrlArr.push(JSON.parse(img.data).data.url)
              wx.hideLoading()
              that.setData({
                cases: imgArr
              })
              that.setData({
                imgUrl: imgUrlArr
              })

            }
          })
        }
      }
    })
  },
  textAreaChange: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  usePerson: function() {
    wx.navigateTo({
      url: '../../my/usePerson/usePerson?doctorId=' + this.data.doctorId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      doctorId: options.id
    })
    let user = wx.getStorageSync("userInfo");
    if (user) {
      let userInfo = JSON.parse(user)
      this.setData({
        userInfo: userInfo
      })
    }

    this.setData({
      orderDate: options.date,
      orderTimes: options.times
    })
    ajax.request({
      url: app.url.doctorDetail,
      data: {
        doctor_id: options.id
      }
    }).then(res => {
      this.setData({
        doctorInfo: res.data
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let info = wx.getStorageSync("selectInfo")
    if (info) {
      this.setData({
        userInfo: JSON.parse(info)
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    let userInfo = wx.getStorageSync("userInfo")
    wx.removeStorageSync("selectInfo")
    if (userInfo) {
      this.setData({
        userInfo: JSON.parse(userInfo)
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})